package com.evolutioninc.wordfinder;

import java.util.*;

public final class WordsUnscrambler {

	public static List<String> getUnscrambleWordsHelper(String word){
		String key = StringUtil.sortWords(word);
		if(!StringUtil.dictionary.get(key.length()).containsKey(key)){
			return null;
		}else{
			return StringUtil.dictionary.get(key.length()).get(key);
		}
	}

	public static ArrayList<List<String>> getUnscrambleWords(String word){
		word = StringUtil.sortWords(word);
		HashSet<String> mySet = getPermutation(word);
		ArrayList<List<String>> solution = new ArrayList<List<String>>(StringUtil.getMaxWordSize()+1);
		
		for(int i = 0; i <= StringUtil.getMaxWordSize(); i++){
			solution.add(new ArrayList<String>());
		}
		
		Iterator<String> iter = mySet.iterator();

		while(iter.hasNext()){
			String wordTmp = iter.next();
			int length = wordTmp.length();
			List<String> list = getUnscrambleWordsHelper(wordTmp);
			if(list != null){
				if(solution.get(length).isEmpty())
					solution.set(length, list);
				else{
					list.addAll(solution.get(length));
					solution.set(length, list);
				}
			}
		}
		return solution;
	}

	private void printSolution(ArrayList<List<String>> solution){
		for(int i = 1; i < StringUtil.getMaxWordSize()+1; i++){
			if(!solution.get(i).isEmpty()){
				System.out.println(i + " Letter Scrabble Words");
				Collections.sort(solution.get(i));
				System.out.println(solution.get(i));
			}
		}
	}
	
	private static HashSet<String> getPermutation(String word){
		HashSet<String> hs = new HashSet<String>();
		if(word.length() == 1){
			hs.add(word);
		}else{
			String firstLetter = word.substring(0, 1);
			HashSet<String> tmpSet = getPermutation(word.substring(1));
			hs = strConcatList(firstLetter, tmpSet);
		}
		
		return hs;
	}
	
	private static HashSet<String> strConcatList(String word, HashSet<String> set){
		HashSet<String> hs = new HashSet<String>();
		Iterator<String> li = set.iterator();
		hs.add(word);
		hs.addAll(set);
		while(li.hasNext()){
			String wordTmp = li.next();
			String newPerm = word.concat(wordTmp);
			if(newPerm.length() <= StringUtil.getMaxWordSize())
				hs.add(newPerm);
		}
		
		return hs;
	}
}

